package meb

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/wechatpay-apiv3/wechatpay-go/core"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// OrderQuery 订单查询
func (ctl *Controller) OrderQuery(ctx *gin.Context) (err error) {
	var (
		args = hgin.ApiReq[OrderWxpayQueryArgs](ctx)
	)

	var order model.Order
	if err = ctl.db.Where("order_id = ?", args.OrderId).Take(&order).Error; err != nil {
		return
	}

	// 待支付订单查询状态
	if order.Status == model.ORDER_UNPAID {
		err1 := wxpayQuery(ctl, order.OrderId)
		// 支付成功，再次查订单信息
		if err1 == nil {
			if err = ctl.db.Where("order_id = ?", args.OrderId).Take(&order).Error; err != nil {
				return
			}
		}
	}

	//已支付订单执行发货
	if order.Status == model.ORDER_PAYSUC {
		order, err = ctl.OrderService.FinishVip(order.OrderId)
		if err != nil {
			return
		}
	}

	hgin.ApiRes(ctx, OrderWxpayQueryBody{
		OrderId: order.OrderId,
		Status:  order.Status,
	})
	return
}

type OrderWxpayQueryArgs struct {
	OrderId string `json:"order_id"`
}

type OrderWxpayQueryBody struct {
	OrderId string            `json:"order_id"`
	Status  model.OrderStatus `json:"status"`
}

// 订单状态改为支付成功
func wxpayQuery(ctl *Controller, orderId string) (err error) {
	var wx = ctl.ConfigService.Wxpay()
	// 待支付，查询微信支付订单
	nativeApi, err := ctl.WxpayService.Native()
	if err != nil {
		return
	}
	t, _, err := nativeApi.QueryOrderByOutTradeNo(context.Background(), native.QueryOrderByOutTradeNoRequest{
		OutTradeNo: core.String(orderId),
		Mchid:      core.String(wx.Mchid),
	})
	if err != nil {
		return
	}
	err = wxpaySuccess(ctl, t)
	if err != nil {
		return
	}
	return
}
